package cc.maxsky.tiebascheme;

import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        //getToolbar().setNavigationIcon(null);

        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings, new SettingsFragment())
                    .commit();
        }

        this.init();
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);
        }
    }

    private void init() {
        getScheme();
        //hideIcon();
    }

    private void getScheme() {
        Intent intent = getIntent();
        Uri uri = intent.getData();
        if (uri != null) {
            Log.w("TAG", uri.toString());

            String path = uri.getPath();
            Log.w("TAG", path);

            path = path.substring(1);

            String scheme = "tb" + path;

            String url = scheme + "://tieba.baidu.com/" + uri.getQuery();

            Log.w("TAG", url);

            Intent targetIntent = new Intent();
            targetIntent.setData(Uri.parse(url));
            targetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(targetIntent);
            finish();
        }
    }

    private void hideIcon() {
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isHide = preference.getBoolean("hide_icon", false);

        Log.w("TAG", String.valueOf(isHide));

        PackageManager packageManager = this.getPackageManager();
        int hide = isHide ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                : PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
        packageManager.setComponentEnabledSetting(getAliasComponentName(), hide, PackageManager.DONT_KILL_APP);
    }

    private ComponentName getAliasComponentName() {
        return new ComponentName(MainActivity.this,
                BuildConfig.APPLICATION_ID + ".MainActivity_Alias");
    }
}
